//
//  ViewController.m
//  iphoneApp
//
//  Created by Liyu on 12-10-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController2.h"
#import "AppDelegate.h"


#import "ASIHTTPRequest.h"
#import "SBJson.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <QuartzCore/QuartzCore.h>

#import "BeautyGirlDetail.h"

#import "MyWaterFLow.h"

#import "MyImageView.h"
#import "UIAlertView+SimpleAlert.h"

#define ImgUrl @"http://img.hb.aicdn.com/%@_fw192"

#define ImgUrl554 @"http://img.hb.aicdn.com/%@_fw554"

@interface ViewController2 ()

@end

@implementation ViewController2
{
    UILabel * label;
    MyWaterFLow * mywaterflow;
    BOOL IsPullToLoad;
    CGSize appFrameSize;
    CGFloat appFrameHeight;
}

@synthesize time=_time;
@synthesize tapimg=_tapimg;
@synthesize dataArr;

-(id)init
{
    self=[super init];
    if (self) {
        IsPullToLoad=NO;
        UIBarButtonItem * back=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(test:)];
        self.navigationItem.backBarButtonItem=back;
        [back release];     
       
    }
    return  self;
}



-(NSMutableArray *) GetImageArr
{
    
    return dataArr;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(NSInteger) waterflow:(MyWaterFLow *)waterflow heightForImageAtIndex:(NSInteger)index 
{
    NSNumber * width=(NSNumber *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"width"];
    NSNumber* height=(NSNumber *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"height"];
    return 105*[height integerValue]/[width integerValue];
}


//重新设置uiimageview的frame uiscrollview的contentsize
-(void) resetImgFrame:(UIImageView *) img ByWidth:(CGFloat) widht AndHeight:(CGFloat) height
{
    CGRect rect=img.frame;
    if (widht>310) {
        rect.size=CGSizeMake(310, 310*height/widht);
    }
    else {
        rect=CGRectMake((310-widht)/2, 0, widht, height);
    }
    img.frame=rect;
}

-(void) MyImageViewTap:(MyImageView *)view
{    
    BeautyGirlDetail * detail=[[BeautyGirlDetail alloc] init];
    detail.getDataDelegate=self;    
    
    
    NSNumber * width=(NSNumber *)[[[dataArr objectAtIndex:view.tag] objectForKey:@"file"] objectForKey:@"width"];
    NSNumber* height=(NSNumber *)[[[dataArr objectAtIndex:view.tag] objectForKey:@"file"] objectForKey:@"height"];
    
    NSString * str=(NSString *)[[[dataArr objectAtIndex:view.tag] objectForKey:@"file"] objectForKey:@"key"];
    
    UIImageView * imgview= [[UIImageView alloc] init];
    imgview.tag=view.tag;
    NSLog(@"index1:%d",view.tag);
    imgview.frame=CGRectMake(0, 0, 310, 310*[height integerValue]/[width integerValue]);
    
    [imgview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:ImgUrl554,str]]];
    
    detail.imgview=imgview;
    [imgview release]; 
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
   
}

-(UIImageView *) waterflow:(MyWaterFLow *)waterflow imageViewForWaterFlowAtIndex:(NSInteger)index
{
    MyImageView * imageview=[[MyImageView alloc] init];
    imageview.delegate=self;
    NSString * str=(NSString *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"key"];
    
    if (index==[dataArr count]-1) {
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:ImgUrl,str]] success:^(UIImage *img,BOOL cache){
            label.hidden=YES;
            
        } failure:^(NSError * error){}];
            }
    else {
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:ImgUrl,str]]];

    }
    
    
    
    return [imageview autorelease];
}

-(NSInteger) numberOfImageInWaterFlow:(MyWaterFLow *)waterflow
{
    return  [dataArr count];
}

-(void) resizeWaterFLow:(BOOL) hide
{
     CGRect frame= mywaterflow.frame;
    if (hide) {
        frame.size.height=frame.size.height+44;
    }
    else {
        frame.size.height=frame.size.height-44;
    }
    mywaterflow.frame=frame;    
}

-(void) myWaterFlowDidScroll:(MyWaterFLow *)waterflow
{    
     
    if (waterflow.contentOffset.y>200 
        && self.navigationController.navigationBarHidden==NO) {
       
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self resizeWaterFLow:YES];
    }
    else if(waterflow.contentOffset.y<200 
            && self.navigationController.navigationBarHidden==YES) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self resizeWaterFLow:NO];

    }
    
    NSInteger maxY= [(NSNumber *)[waterflow.columnHeightArr objectAtIndex:[waterflow getMaxHeightColumnIndexInArray]] integerValue];       
    

    if (waterflow.contentOffset.y+waterflow.frame.size.height >= maxY-40) {
         
        IsPullToLoad=YES;
        
        label.hidden=NO;
        
        [waterflow setContentOffset:waterflow.contentOffset animated:YES];
        
        waterflow.pageIndex=waterflow.pageIndex+1;
        
        NSNumber * maxid=(NSNumber *)[[dataArr lastObject] objectForKey:@"pin_id"];
        
        NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"http://huaban.com/favorite/beauty/?max=%d&limit=20&wfl=1",[maxid integerValue]]];   
        	
        //NSURL * url=[NSURL URLWithString:@"http://huaban.com/favorite/beauty/?max=30659493&limit=20&wfl=1&h9ctggt4&max=30649291&limit=20&wfl=1"];        
        
        ASIHTTPRequest * req=[ASIHTTPRequest requestWithURL:url];
        [req addRequestHeader:@"X-Request" value:@"JSON"];
        [req addRequestHeader:@"X-Requested-With" value:@"XMLHttpRequest"];
        [req setRequestMethod:@"GET"];
        [req setDelegate:self];
        [req startAsynchronous];
    
        NSLog(@"diao yong le a,%d",waterflow.pageIndex);
    }
    else 
    {
        IsPullToLoad=NO;
    }
    
}



-(void)viewWillAppear:(BOOL)animated
{
    if ([UIApplication sharedApplication].statusBarHidden) {
//        [UIApplication sharedApplication].statusBarHidden=NO;
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    }
    
    if (self.navigationController.navigationBarHidden) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
//        self.navigationController.navigationBarHidden=NO;
    }
}

- (void)viewDidLoad
{    
    
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    CGFloat tipLabelHeight=30.0f;
    
    appFrameSize=[[UIScreen mainScreen] applicationFrame].size;
    appFrameHeight=appFrameSize.height;
    
     self.navigationController.navigationBar.autoresizesSubviews=NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBarBackgroundRetro.png"] forBarMetrics:UIBarMetricsDefault ];      
        
    
    label=[[UILabel alloc] initWithFrame:CGRectMake(0, appFrameHeight-tipLabelHeight, appFrameSize.width, tipLabelHeight)];
    label.backgroundColor=[UIColor colorWithWhite:1.0 alpha:0.5];
    label.textAlignment=UITextAlignmentCenter;      
    label.text=@"亲，美图马上来哦！";
    label.textColor=[UIColor blackColor];
   
    
    //NSURL * url=[NSURL URLWithString:@"http://huaban.com/search/?q=%E5%A5%BD%E9%95%BF%E5%95%8A"];
    NSURL * url=[NSURL URLWithString:@"http://huaban.com/favorite/beauty/"];
    //NSURL * url=[NSURL URLWithString:@"http://huaban.com/weibonai/pins/"];
    ASIHTTPRequest * req=[ASIHTTPRequest requestWithURL:url];
    [req startAsynchronous];   
    [req setDelegate:self];
    
    self.title=@"NewBeauty";
    
    
    mywaterflow=[[MyWaterFLow alloc] initWithFrame:CGRectMake(0, 0, 320, appFrameHeight-44)];
    
    mywaterflow.dataSource=self;
    mywaterflow.mywaterFlowDelegate=self;
    [self.view addSubview:mywaterflow];
    [self.view addSubview:label];
    
    [label release];    
    [mywaterflow release];   
    


    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString * str=[request responseString];
    
    if (IsPullToLoad) {
        id data=[str JSONValue];        
        [dataArr addObjectsFromArray:(NSArray *)[data objectForKey:@"pins"]]; 
    }
    else {
        NSRange  dataRange=[str rangeOfString:@"[\"pins\"] = "];
        //NSRange  dataRange=[str rangeOfString:@"[\"user\"] = "];
        str=[str substringFromIndex:NSMaxRange(dataRange)];
        
        NSRange dataEndRange=[str rangeOfString:@"app.page"];
        //NSRange dataEndRange=[str rangeOfString:@"app._csr"];
        str=[str substringToIndex:dataEndRange.location-2];
        
        //id str1=[str JSONValue];
        //dataArr=[str1 objectForKey:@"pins"];
        dataArr=[str JSONValue];
    }  
    
    [mywaterflow LoadWaterFlow];

    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
